package com.relytosoft.mizar.media.host.job;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.relytosoft.dubhe.common.api.entity.system.SysMsgRepeat;
import com.relytosoft.dubhe.common.api.service.RemoteMsgRepeatService;
import com.relytosoft.dubhe.common.redis.utils.RedisUtil;
import com.relytosoft.mizar.media.common.emqx.client.MqttOp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 消息补偿Job
 *
 * @author Jierry
 * @version 2022/4/24.
 */
@Component
public class MqRepeatJob {

    @Resource
    private RemoteMsgRepeatService remoteMsgRepeatService;

    private static final Logger log = LoggerFactory.getLogger(MqRepeatJob.class);
    private final AtomicBoolean jobDone;

    public MqRepeatJob() {
        this.jobDone = new AtomicBoolean(true);
    }

//    @Scheduled(cron = "0 0/5 * * * ?")
//    @Async("asyncJobExecutor")
//    public void mqRepeatJobHandler(){
//        log.info("MqRepeatJob-start");
//        if (!this.jobDone.get()) {
//            log.info("MqRepeatJob尚未执行结束，等待执行");
//            return;
//        }
//        String uuid = UUID.randomUUID().toString();
//        if (RedisUtil.lock("MqRepeatJob_lock",uuid,60000)){
//            this.jobDone.set(false);
//            try {
//                LambdaQueryWrapper<SysMsgRepeat> wrapper = Wrappers.lambdaQuery();
//                wrapper.eq(SysMsgRepeat::getStatus,0);
//                wrapper.orderByAsc(SysMsgRepeat::getId);
//                SysMsgRepeat msgRepeat = remoteMsgRepeatService.getOne(wrapper);
//                if (ObjectUtil.isNotEmpty(msgRepeat)){
//                    MqttOp.publish(msgRepeat.getTopicName(),msgRepeat.getContent());
//                    remoteMsgRepeatService.updateSysMsgRepeatStatus(msgRepeat.getId(),"JobSystem");
//                    log.info("MqRepeatTask-resend:"+msgRepeat.getTopicName());
//                }
//                log.info("MqRepeatJob-end");
//            }
//            catch (Exception ex){
//                log.error("MqRepeatTask-error:"+ex.getMessage());
//            }
//            finally {
//                this.jobDone.set(true);
//                RedisUtil.unLock("MqRepeatJob_lock",uuid);
//            }
//        }
//
//    }
}
